<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 */
class HongdouController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );


        $data = array();
        $data['gymchtId'] = $this->config['mch_id'];
        $data['tradeSn'] = $return['orderid'];
        $data['orderAmount'] = $return['amount']*100;
        $data['goodsName'] = 'apple';
        $data['expirySecond'] = 120;

        switch($this->config['paytype']){
            //支付宝
            case 3:
            case 4:
            case 17:
            case 18:
            case 21:
            case 22:
                $data['tradeSource'] = '1';
                break;
            default:
                $this->showmessage('不支持此产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['notifyUrl'] = $return['notifyurl'];

        ksort($data);
        $str = httpstr($data)."&key=".$this->config['signkey'];

        $data['sign'] = strtoupper(md5($str));

        $res = curl($this->config['gateway'], httpstr($data));

        //echo '<pre/>'; print_r($data); echo "请求地址：" . $this->config['gateway'].'<br/>'; print_r($res); exit;

        if(!$res){
            $this->showmessage('获取数据失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $res = json_decode($res, true);
        if(empty($res)){
            $this->showmessage('获取的数据格式不正确!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $code = $res['code_url'];
        if(!$code){
            if($res['message']){
                $this->showmessage($res['message'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage('获取二维码失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $paytype = transArr( C("PAYTYPES"), "id");
        $this->assign("wap_url", $code);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=1&data=".$code);
        switch($this->config['paytype']){
            //微信
            case 1:
                $this->display("WeiXin/weixin");
                break;
            //支付宝扫码
            case 3:
            case 4:
            case 17:
            case 18:
            case 21:
            case 22:
                header("Location:{$code}");
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
        $this->debug_callback();
        if(!$this->checkip(getIP(),['159.138.129.198'])){
            //exit("wrong");
        }

        $p = file_get_contents('php://input');

        //$p = '{"gymchtId":"grdlcl0001","orderAmount":1000,"pay_result":"0","sign":"FA1B8EA1473ECE3D55D4D00E370B8A1B","t0Flag":"0","timeEnd":"20180917212003","tradeSn":"201809172119561397488","transaction_id":"20180917000046755394"}';

        $p = json_decode($p, true);
        /*Array
(
    [gymchtId] => grdlcl0001
    [orderAmount] => 1000
    [pay_result] => 0
    [sign] => FA1B8EA1473ECE3D55D4D00E370B8A1B
    [t0Flag] => 0
    [timeEnd] => 20180917212003
    [tradeSn] => 201809172119561397488
    [transaction_id] => 20180917000046755394
)
        );*/

        if(empty($p)){
            exit("no_data");
        }

        $sign = $p['sign'];

        //获取订单信息
        $orderid = $p['tradeSn'];
        $find = $this->checkOrderNotify($orderid);

        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "pay_orderid_rd"=>htmlspecialchars($p['transaction_id']),
            "pay_true" => floatval($p['orderAmount'] / 100),
        ));

        if(abs($find['pay_amount'] - $p['orderAmount']/100) > 1){
            exit("illegal");
        }

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        if(!$this->config){
            exit("get_tongdao_fail");
        }

        if(intval($p['pay_result']) != 0){
            exit("pay_fail");
        }

        unset($p['sign']);
        ksort($p);

        $str = httpstr($p)."&key=".$this->config['signkey'];

        $sign2 = strtoupper(md5($str));

        if($sign !== $sign2){
            echo 'sign_wrong';exit;
        }

        $this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){
        echo '处理成功'; exit;
    }
}